package com.airforce.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.util.UUID;

public class MD5BASE64Util {
	private static BASE64Encoder encoder = new BASE64Encoder();
	private static BASE64Decoder decoder = new BASE64Decoder();
	
	public static String base64encode(String s){
		try{
			String encodeStr = encoder.encode(s.getBytes());
			
			return encodeStr;
		}catch(Exception e){
			return s;
		}
	}
	
	public static String base64decode(String s){
		try{
			String decodeStr = new String(decoder.decodeBuffer(s));
						
			return decodeStr;
		}catch(Exception e){
			return s;
		}
	}
	
	public static byte[] md5encode(byte[] input){
		byte[] digestedValue = null;
		try{
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(input);
			digestedValue = md.digest();
		}catch(Exception e){
			e.printStackTrace();
		}
		return digestedValue;
	}
	public static String md5base64encode(String input){
		byte[] pmb = MD5BASE64Util.md5encode(input.getBytes());
	    String pms = new String(pmb);
		String pm_base64=MD5BASE64Util.base64encode(pms);
		return pm_base64;
	}
	public static void main(String args[]){

		String[] str_66 = MD5BASE64Util.base64decode("b0orQ3hkd2VlVUdralk1cUlZbDBuUT09LG9aYzZHNU16QjZ5NHNwbzFQRTB6ZFI5cDdpZlEsc2Fs\\ndA==").split(",");
		String openid=str_66[1];
		System.out.println(JsonUtil.toJson(str_66));

		//测试BASE64加密
		System.out.println("------------------------------------");
		String str = "wlj1234";
		String ret = null;
		ret = base64encode(str);
		System.out.println("base64加密前:"+str+" \n加密后:"+ret);
		 
		//测试BASE64解密
		System.out.println("------------------------------------");
		String str1 = ret;
		ret = base64decode(ret);
	    System.out.println("base64解密前:"+str1+"\n 解密后:"+ret);
	    
	    //测试MD5加密，MD5是不可逆置的
	    System.out.println("------------------------------------");
	    String str2 = str;
	    byte[] ret1 = null;
	    ret1 = md5encode(str2.getBytes());	
	    System.out.println("MD5解密前:"+str2+" \n解密后:"+new String(ret1));
	     
	    //将MD5和BASE64结合起来使用
	    System.out.println("------------------------------------");
	    String str3 = str;
	    byte[] md5str = md5encode(str3.getBytes());
	    String temp = new String(md5str);
	    String basestr1 = base64encode(temp);
	    System.out.println("MD5加密后:"+temp+"\nBASE64加密后:"+basestr1);
	    String basestr2 = base64decode(basestr1);
	    System.out.println("BASE64加密后:"+basestr1+"\nBASE64解密后:"+basestr2);
	    System.out.println("------------------------------------");


		System.out.println(getOrderIdByUUId());
	}

	public static String getOrderIdByUUId() {
		int machineId = 1;//最大支持1-9个集群机器部署
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if(hashCodeV < 0) {//有可能是负数
			hashCodeV = - hashCodeV;
		}
//         0 代表前面补充0
//         4 代表长度为4
//         d 代表参数为正数型
		return "BMW"+ machineId+ String.format("%015d", hashCodeV);
	}


}